package com.jjty.dataGenerator.exception;

import com.jjty.dataGenerator.common.ApiResult;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handleException(MethodArgumentNotValidException ex){
        System.out.println("出现异常：MethodArgumentNotValidException");
        String message = ex.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return ApiResult.doFailure(message);
    }

    @ExceptionHandler(ServiceException.class)
    public ApiResult handleException(ServiceException e){
        System.out.println("出现异常：ServiceException");
        return ApiResult.doFailure(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ApiResult handleException(Exception e){
        e.printStackTrace();
        System.out.println("出现异常：Exception");
        return ApiResult.doFailure(e.getMessage());
    }

}
